import os, sys
from time import time
from fastapi import FastAPI, File, UploadFile, Response, Form, Request
from config import settings
from loguru import logger
from fastapi.responses import FileResponse, StreamingResponse
import requests
import cv2
from utils import file_storage
import traceback

app = FastAPI(debug=False)

logger.add(
    os.path.join('logs', '{time:YYYY-MM-DD}.txt'),  # 日志文件路径
    format="{time:YYYY-MM-DD HH:mm:ss} {level} {message}",  # 日志格式
    rotation="00:00",  # 每天早上00:00分切割日志
    retention="10 days",  # 保留10天的日志
    # compression="zip", # 压缩日志
    level="DEBUG"  # 设置日志级别
)


@app.post("/upload")
async def upload_file(file: UploadFile = File(...)):
    filename = file.filename
    file = file.file
    ext = filename.split('.')[-1]
    try:
        uuid = file_storage.save(file.read(), ext)
        return {'uuid': uuid, "success": True}
    except Exception as e:
        logger.error(f'上传失败：{e}')
        return {"error": str(e), "success": False}


@app.get("/files/{uuid}")
async def get_file(uuid: str):
    try:
        file_path = file_storage.get(uuid)
        return FileResponse(path=file_path, filename='filename', media_type='image/jpeg')
    except Exception as e:
        logger.error(f'获取文件失败：{e}')
        return {"error": str(e), "success": False}


@app.post("/request")
async def request_server(request: Request):
    form_data = await request.form()
    address = form_data.get('address')
    params = {}
    for key, value in form_data.items():
        if key not in ['address', 'uuid']:
            params[key] = value
    uuid = form_data.get('uuid')
    try:
        file_path = file_storage.get(uuid)
        response = requests.post(
            address, files={'file': open(file_path, 'rb')}, data=params)
        print(response)
        response = response.json()
        if response['success']:
            return {"success": True, 'results': response['results'], 'timestamp': time()}
        else:
            logger.error(f'请求失败：{response["error"]}')
            return {"success": False, "error": response['error']}
    except Exception as e:
        line = traceback.format_exc().splitlines()[-3]
        logger.error(f'请求失败：{e} | {line}')
        return {"success": False, "error": str(e)}


@app.post("/crop")
async def crop_image(uuid: str = Form(...), x1: float = Form(...), y1: float = Form(...), x2: float = Form(...), y2: float = Form(...)):
    try:
        file_path = file_storage.get(uuid)
        img = cv2.imread(file_path)
        h, w = img.shape[:2]
        x1 = int(x1 * w)
        y1 = int(y1 * h)
        x2 = int(x2 * w)
        y2 = int(y2 * h)
        img = img[y1:y2, x1:x2]
        uuid = file_storage.add(img, 'jpg')
        return {"success": True, "uuid": uuid}
    except Exception as e:
        logger.error(f'裁剪失败：{e}')
        return {"success": False, "error": str(e)}